package com.yuanheng100.ems4j.service.h2;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.h2.tools.Console;
import org.h2.tools.RunScript;

import java.sql.SQLException;

/**
 * Created by j4love on 2016/12/14.
 * Description : H2 数据库的初始化操作，执行指定路径下的SQL脚本。
 *               在项目第一次启动的时候创建表结构,以后启动不应再创建
 *               表，以免造成数据丢失。所以请保证所指定的sql脚本中的
 *               建表语句有 IF NOT EXISTS 语句。
 */
public class H2DBInitialization {

    private static final transient Logger logger = LogManager.getLogger(H2DBInitialization.class);

    private String user;

    private String password;

    private String url;

    private String scriptPath;

    /**
     * 执行指定的SQL脚本
     */
    public void runScript(){
        String log;
        try {
            log = new StringBuilder("初始化 H2 数据库,url[")
                    .append(this.url)
                    .append("],执行SQL脚本[")
                    .append(this.scriptPath)
                    .append("]").toString();
            logger.debug(log);
            new Console().runTool("-user",this.user,"-password",this.password,"-url","-script",this.scriptPath);
            new RunScript().runTool();
            log = new StringBuilder("初始化 H2 数据库,url[")
                    .append(this.url)
                    .append("]成功.")
                    .toString();
            logger.debug(log);
            this.password = null;
        } catch (SQLException e) {
            log = new StringBuilder("初始化 H2 数据库,url[")
                    .append(this.url)
                    .append("]失败.")
                    .toString();
            logger.error(log,e);
        }
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setScriptPath(String scriptPath) {
        this.scriptPath = scriptPath;
    }
}
